package com.xiaode.validator;

import cn.hutool.core.collection.CollectionUtil;
import com.jfinal.core.Controller;
import com.jfinal.kit.StrKit;
import com.jfinal.validate.Validator;
import com.xiaode.exce.EnumError;
import com.xiaode.plugin.SensitiveWord.SensitivewordFilter;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Objects;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author 张烨
 * @description 基础校验器
 * @time 2016年10月28日
 */
public abstract class BaseValidator extends Validator {

    //普通字符串长度限制
    public static final String STRING_SIZE = "^.{0,20}$";
    //6-20未用户名
    public static final String USER_NAME = "^[A-Za-z0-9]{6,20}$";
    //密码必须是数字和字母
//    public static final String USER_PASSWORD = "^(?![a-zA-z]+$)(?!\\d+$)(?![!@#$%^&*]+$)[a-zA-Z\\d!@#$%^&*-]{6,32}$";
    public static final String USER_PASSWORD = "[0-9a-zA-Z]";
    //手机号
    public static final String PHONE = "^1[3456789]\\d{9}$";
    // 6位数字的验证码
    public static final String VCode = "\\d{6}$";
    //身份证校验，初级校验，具体规则有一套算法
    public static final String ID_CARD = "^\\d{15}$|^\\d{17}([0-9]|X)$";
    //邮箱
    protected static final String emailAddressPatternOrPhone =
            "(\\b(^['_A-Za-z0-9-]+(\\.['_A-Za-z0-9-]+)*@([A-Za-z0-9-])+(\\.[A-Za-z0-9-]+)*((\\.[A-Za-z0-9]{2,})|(\\.[A-Za-z0-9]{2,}\\.[A-Za-z0-9]{2,}))$)\\b)|(^\\\\d{15}$|^\\\\d{17}([0-9]|X)$)";


    {
        this.setShortCircuit(true);
    }

    

    /**
     * 0-20字符长度
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateStringSize(String field, String errorKey, String errorMsg) {
        validateRegex(field, STRING_SIZE, false, errorKey, errorMsg);
    }

    /**
     * 验证手机号格式
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validatePhone(String field, String errorKey, String errorMsg) {
        validateRegex(field, PHONE, false, errorKey, errorMsg);
    }

    /**
     * 账号号格式
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validatePhoneOrPhon(String field, String errorKey, String errorMsg) {
        validateRegex(field, emailAddressPatternOrPhone, false, errorKey, errorMsg);
    }

    /**
     * 验证身份证号码
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateIdCard(String field, String errorKey, String errorMsg) {
        validateRegex(field, ID_CARD, false, errorKey, errorMsg);
    }
    
    /**
     * 6位数字的验证码
     *  
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateVCode(String field, String errorKey, String errorMsg) {
        validateRegex(field, VCode, false, errorKey, errorMsg);
    }

   

    /**
     * 校验是否有敏感词
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateWord(String field, String errorKey, String errorMsg){
        if (StrKit.isBlank(controller.getPara(field))) {
            addError(errorKey, errorMsg);
        }
        String value = controller.getPara(field);
//        SensitivewordFilter sensitivewordFilter = new SensitivewordFilter();
        /**校验是否有敏感词*/
        Set<String> set = SensitivewordFilter.getSensitiveWord(value, 1);
        if (!CollectionUtil.isEmpty(set)){
            addError(errorKey, EnumError.WORLD_FAIL.getMsg()+set);
        }
    }
    /**
     * 校验是否有敏感词不校验是否为空
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateWordIsNull(String field, String errorKey, String errorMsg){
        if (StrKit.isBlank(controller.getPara(field))) {
            return;
        }
        String value = controller.getPara(field);
//        SensitivewordFilter sensitivewordFilter = new SensitivewordFilter();
        /**校验是否有敏感词*/
        Set<String> set = SensitivewordFilter.getSensitiveWord(value, 1);
        if (!CollectionUtil.isEmpty(set)){
            addError(errorKey, EnumError.WORLD_FAIL.getMsg()+set);
        }
    }


    protected void validateSize(String field, String errorKey, String errorMsg) {
        validateRegex(field, PHONE, false, errorKey, errorMsg);
    }

    /**
     * 判断字符串格式是否是规定的格式
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateTime(String field, String errorKey, String errorMsg) {
        validateRequiredString(field, errorKey, errorMsg);
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String value = controller.getPara(field);
        int flag = 1;
        try {
            //Java 8 新添API 用于解析日期和时间
            LocalDateTime.parse(value, dtf);
        } catch (Exception e) {
            flag = 0;
        }
        if (flag == 0) {
            addError(errorKey, errorMsg);
        }

    }

    /**
     * 判断时间
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateSelf(String field, String errorKey, String errorMsg) {
        validateRequiredString(field, errorKey, errorMsg);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String value = controller.getPara(field);
//        Date date = null;
        try {
            Date date = simpleDateFormat.parse(value);
            if (Objects.isNull(date)){
                addError(errorKey, errorMsg);
            }
            System.out.println(date);
        } catch (ParseException e) {
            e.printStackTrace();
        }


    }

//    public static void main(String[] args) throws ParseException {
//        String time = "2025-07-02 13:01:00";
////        String time ="2025-11-20 11:10:10";
////        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
////        Date date = simpleDateFormat.parse(s);
////        Date date = simpleDateFormat.parse(time);
////        System.out.println(date);
//
//
//
//        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//
//        Date date = null;
//        try {
//            date = simpleDateFormat.parse(time);
//            System.out.println(date);
//        } catch (ParseException e) {
//        }
//        if (Objects.isNull(date)){
//            System.out.println("++++++++++");
//        }
//    }

    /**
     * 判断字符串格式是否是规定的格式
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateHour(String field, String errorKey, String errorMsg) {
        validateRequiredString(field, errorKey, errorMsg);
        //时间HH:mm:ss 正则表达式
        String timeReg1 = "([0-1]?[0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
        String value = controller.getPara(field);
        Pattern compile = Pattern.compile(timeReg1);
        Matcher matcher = compile.matcher(value);

        //判断如果为false 则添加异常
        if (!matcher.matches()) {
            addError(errorKey, errorMsg);
        }
    }

    /**
     * 判断id 职能为大于0的数
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateId(String field, String errorKey, String errorMsg) {
        validateInteger(field, errorKey, errorMsg);
        String value = controller.getPara(field);

        if ((value.matches("[0-9]+")) && (Integer.parseInt(value) > 0)) {
            //如果以上条件成立，则str是正整数
        } else {
            addError(errorKey, errorMsg);
        }
    }

    /**
     * 判断Long类型数据是否为空
     *
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateLongValueZ(String field, String errorKey, String errorMsg) {
        String value = controller.getPara(field);
        if (StrKit.isBlank(value)) {
            addError(errorKey, errorMsg);
            return;
        }
        if ((value.startsWith("N") || value.startsWith("n"))) {
            value = "-" + value.substring(1);
            addError(errorKey, errorMsg);
        } else {
            try {
                Long.parseLong(value.trim());
            } catch (Exception e) {
                addError(errorKey, errorMsg);
            }
        }
    }

    protected void validateBigDecimal(String field, String errorKey, String errorMsg) {
        String value = controller.getPara(field);
        if (StrKit.isBlank(value)) {
            addError(errorKey, errorMsg);
            return;
        }
        if ((value.startsWith("N") || value.startsWith("n"))) {
            value = "-" + value.substring(1);
            addError(errorKey, errorMsg);
        } else {
            try {
                BigDecimal.valueOf(Double.valueOf(value.trim()));
            } catch (Exception e) {
                addError(errorKey, errorMsg);
            }
        }
    }

    /**
     * 校验分页参数
     * @param field
     * @param min
     * @param errorKey
     * @param errorMsg
     */
    protected void validatePage(String field,Integer min, String errorKey, String errorMsg){
        String value = controller.getPara(field);
        if (StrKit.isBlank(value)) {
            addError(errorKey, errorMsg);
            return;
        }
        if ((value.startsWith("N") || value.startsWith("n"))||Integer.valueOf(value)<min) {
            value = "-" + value.substring(1);
            addError(errorKey, errorMsg);
        }else {
            try {
                Integer.valueOf(value.trim());
            } catch (Exception e) {
                addError(errorKey, errorMsg);
            }
        }
    }

    /**
     * 校验年
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateYear(String field, String errorKey, String errorMsg){
        String value = controller.getPara(field);
        if (StrKit.isBlank(value)) {
            addError(errorKey, errorMsg);
            return;
        }
        if ((value.startsWith("N") || value.startsWith("n"))) {
            value = "-" + value.substring(1);
            addError(errorKey, errorMsg);
        }else {
            try {
                Integer.valueOf(value.trim());
            } catch (Exception e) {
                addError(errorKey, errorMsg);
            }
        }
        if (value.toCharArray().length<4||Integer.valueOf(value)<1000){
            addError(errorKey, errorMsg);
        }
    }

    /**
     * 校验月份
     * @param field
     * @param errorKey
     * @param errorMsg
     */
    protected void validateMonth(String field, String errorKey, String errorMsg){
        String value = controller.getPara(field);
        if (StrKit.isBlank(value)) {
            addError(errorKey, errorMsg);
            return;
        }
        if ((value.startsWith("N") || value.startsWith("n"))) {
            value = "-" + value.substring(1);
            addError(errorKey, errorMsg);
        }else {
            try {
                Integer.valueOf(value.trim());
            } catch (Exception e) {
                addError(errorKey, errorMsg);
            }
        }
        Integer month = Integer.valueOf(value);
        if (month<1||month>12){
            addError(errorKey, errorMsg);
        }
    }

//    /**
//     * 校验字符串，如果为空，就设置默认值为空字符串""
//     * @param field
//     * @param errorKey
//     * @param errorMsg
//     */
//    protected void validateString(String field, String errorKey, String errorMsg){
//        String para = controller.getPara(field);
//        if (StrKit.isBlank(para)){
//            para = "";
//        }
//
//    }


    @Override
    protected void handleError(Controller c) {
        c.setAttr("result", false);
        c.renderJson(new String[]{"result", "msg"});
    }


}
